<?php

namespace common\models\base;

use Yii;
use common\helpers\StringHelper;
use common\helpers\IpHelper;
use common\models\user\UserAddress;
use common\helpers\PinyinHelper;

/**
 * This is the model class for table "{{%base_district}}".
 *
 * @property int $id 地区ID
 * @property int $parent_id 父级节点ID
 * @property string $name 地区名称
 * @property string $code 地区码
 * @property string|null $abbr 地区简称
 * @property string|null $letter 拼音首字母
 * @property string|null $pinyin 拼音
 * @property int $level 地区层级
 */
class BaseDistrict extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%base_district}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['parent_id', 'level'], 'integer'],
            [['name', 'code'], 'required'],
            [['name'], 'string', 'max' => 50],
            [['code'], 'string', 'max' => 6],
            [['abbr'], 'string', 'max' => 20],
            [['letter'], 'string', 'max' => 1],
            [['pinyin'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => '地区ID',
            'parent_id' => '父级节点ID',
            'name' => '地区名称',
            'code' => '地区码',
            'abbr' => '地区简称',
            'letter' => '拼音首字母',
            'pinyin' => '拼音',
            'level' => '地区层级',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getParent() {
        return $this->hasOne(static::class, ['id' => 'parent_id']);
    }

    /**
     * {@inheritdoc}
     */
    public function getChildren() {
        return $this->hasMany(static::class, ['parent_id' => 'id']);
    }

    /**
     * {@inheritdoc}
     */
    public static function getRegions() {
        return require Yii::getAlias('@common/data/area/region.php');
    }

    /**
     * {@inheritdoc}
     */
    public function getRegionParent() {
        if ($this->parent_id) {
            return $this->parent_id;
        }
        $precode = substr($this->code, 0, 2);
        $regions = static::getRegions();
        foreach ($regions as $region) {
            if (in_array($precode, $region['codes'])) {
                return $region['id'];
            }
        }
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function fieldConfigs() {
        return [
            'id',
            'name',
            'code',
            'abbr',
            'level',
            'parent_id' => 'regionParent'
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function getUnifinedName($code) {
        $data = static::find()
        ->where(['code' => array_unique($code)])
        ->orderBy(['level' => SORT_ASC])
        ->select('name')
        ->column();
        return implode(' ', $data);
    }

    /**
     * {@inheritdoc}
     */
    public static function loadDist() {
        $provinces = static::find()->andWhere([
            'parent_id' => 0
        ])->all();
        $province = ArrayHelper::map($provinces, 'code', 'name');
        $citys = static::find()->andWhere([
            'level' => 2
        ])->all();
        $city = ArrayHelper::map($citys, 'code', 'name');
        $countys = static::find()->andWhere([
            'level' => 3
        ])->all();
        $county = ArrayHelper::map($countys, 'code', 'name');
        return compact('province', 'city', 'county');
    }

    /**
     * {@inheritdoc}
     */
    public static function loadTree() {
        return static::find()->all();
    }

    /**
     * {@inheritdoc}
     */
    public static function loadRegionList() {
        $query = static::find()->alias('t');
        $query->joinWith('parent parent');
        $query->andWhere([
            'or',
            ['t.parent_id' => 0],
            ['parent.parent_id' => 0],
        ]);

        return $query->all();
    }

    /**
     * {@inheritdoc}
     */
    public static function loadRegion() {
        $data = static::find()->andWhere([
            'parent_id' => 0
        ])->all();
        $areas = [];
        $regions = static::getRegions();
        foreach ($regions as $region) {
            $regionId = $region['id'];
            $areas[$regionId] = [
                'id' => $regionId,
                'name' => $region['name'],
                'code' => '',
                'abbr' => '',
                'level' => 0,
                'parent_id' => 0,
                'children' => [],
                'checks' => [],
                'disabled' => false,
            ];
        }
        foreach ($data as $item) {
            $regionId = $item->getRegionParent();
            $region = ArrayHelper::getValue($regions, $regionId);
            $areas[$regionId]['children'][] = $item;
        }
        return array_values($areas);
    }

    /**
     * @return \common\db\ActiveQuery
     */
    public static function findByAreaCode($code) {
        return static::find()->andWhere([
            'code' => $code
        ]);
    }

}
